#include "MCP2515.h"
#include "IO_DEF.h"

spi_device_handle_t spi;


void MCP_SPI_PRE_CB(spi_transaction_t *t)
{

}


void MCP_SPI_MASTER_Init(void)
{
    esp_err_t ret;
    spi_bus_config_t buscfg=
    {
        .miso_io_num = MCP_MISO,
        .mosi_io_num = MCP_MOSI,
        .sclk_io_num = MCP_SCK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 8,
    };
    spi_device_interface_config_t devcfg=
    {
        .clock_speed_hz=10*1000*1000,           //Clock out at 10 MHz
        .mode=0,                                //SPI mode 0
        .spics_io_num=MCP_CS,               //CS pin
        .queue_size=7,                          //We want to be able to queue 7 transactions at a time
        .pre_cb=MCP_SPI_PRE_CB,  //Specify pre-transfer callback to handle D/C line
    };
    //Initialize the SPI bus
    ret = spi_bus_initialize(SPI3_HOST, &buscfg, SPI_DMA_CH_AUTO);
    ESP_ERROR_CHECK(ret);
    ret=spi_bus_add_device(SPI3_HOST, &devcfg, &spi);
    ESP_ERROR_CHECK(ret);
}

void MCP_SPI_WRITE(uint8_t DATA)
{
    esp_err_t ret;
    spi_transaction_t t;
    memset(&t, 0, sizeof(t));       //Zero out the transaction
    t.length=8;                     //Command is 8 bits
    t.flags=SPI_TRANS_USE_TXDATA;
    t.tx_data[0]=DATA;
    ret=spi_device_polling_transmit(spi, &t);  //Transmit!
    assert(ret==ESP_OK);            //Should have had no issues.
}

uint8_t MCP_SPI_READ(void)
{
    esp_err_t ret;
    spi_transaction_t t;
    memset(&t, 0, sizeof(t));       //Zero out the transaction
    t.length=8;                     //Command is 8 bits
    t.flags=SPI_TRANS_USE_RXDATA;
    ret=spi_device_polling_transmit(spi, &t);  //Transmit!
    assert(ret==ESP_OK);            //Should have had no issues.
    return t.rx_data[0];
}


uint8_t MCP_SPI_TEST(void)
{
    uint8_t RES=0;
    // When using SPI_TRANS_CS_KEEP_ACTIVE, bus must be locked/acquired
    spi_device_acquire_bus(spi, portMAX_DELAY);
    MCP_SPI_WRITE(0x03);
    MCP_SPI_WRITE(0x1F);
    RES=MCP_SPI_READ();
    spi_device_release_bus(spi);
    return RES;
}



































